package com.hmall.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.clients.AddressClient;
import com.hmall.common.clients.ItemClient;
import com.hmall.common.pojo.Address;
import com.hmall.common.pojo.Item;
import com.hmall.order.mapper.OrderDetailMapper;
import com.hmall.order.mapper.OrderLogisticsMapper;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.Order;
import com.hmall.order.pojo.OrderDetail;
import com.hmall.order.pojo.OrderDto;
import com.hmall.order.pojo.OrderLogistics;
import com.hmall.order.service.IOrderService;
import com.hmall.order.utils.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private AddressClient addressClient;
    @Autowired
    private OrderLogisticsMapper orderLogisticsMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Override
    public Long saveOrder(OrderDto dto) {

        Item item = itemClient.getById(dto.getItemId());
        Long totalFee = item.getPrice() * dto.getNum();
        Order order = new Order();
        order.setPaymentType(dto.getPaymentType());
        order.setTotalFee(totalFee);
        order.setStatus(1);
        order.setPayTime(new Date());
        order.setUpdateTime(new Date());
        order.setCreateTime(new Date());
        order.setUserId(UserThreadLocal.get());
        this.save(order);
        OrderDetail detail = new OrderDetail();
        detail.setItemId(dto.getItemId());
        detail.setNum(dto.getNum());
        detail.setOrderId(order.getId());
        detail.setName(item.getName());
        detail.setPrice(item.getPrice());
        detail.setImage(item.getImage());
        detail.setSpec(item.getSpec());
        detail.setCreateTime(new Date());
        detail.setUpdateTime(new Date());
        orderDetailMapper.insert(detail);

        Address address = addressClient.findAddressById(dto.getAddressId());
        OrderLogistics logistics = new OrderLogistics();
        logistics.setOrderId(order.getId());
        logistics.setContact(address.getContact());
        logistics.setPhone(address.getMobile());
        logistics.setProvince(address.getProvince());
        logistics.setCity(address.getCity());
        logistics.setTown(address.getTown());
        logistics.setStreet(address.getStreet());
        logistics.setCreateTime(new Date());
        logistics.setUpdateTime(new Date());
        orderLogisticsMapper.insert(logistics);
        itemClient.updateStock(dto.getItemId(),dto.getNum());
        return order.getId();
    }

    /**
     * 删除超时订单
     */
    @Override
    public void deleteOverTime() {
//        // 获取当前时间
//        ZonedDateTime now = ZonedDateTime.now(ZoneId.systemDefault());
//        // 减去30分钟
//        ZonedDateTime thirtyMinutesAgo = now.minus(30, ChronoUnit.MINUTES);
        LocalDateTime thirtyMinutesAgo = LocalDateTime.now().minus(30, ChronoUnit.MINUTES);
        List<Order> list = lambdaQuery().select(Order::getId)
                .eq(Order::getStatus, 1)
                .lt(Order::getCreateTime, thirtyMinutesAgo)
                .list();

        for (Order order : list) {
            OrderDetail detail = orderDetailMapper.findByOrderId(order.getId());
            itemClient.restock(detail.getItemId(),detail.getNum());
//            orderDetailMapper.deleteById(order.getId());
//            // 删除物流信息
//            orderLogisticsMapper.deleteById(order.getId());
            // 更新订单状态
            lambdaUpdate().set(Order::getStatus,5)
                    .set(Order::getCloseTime,new Date())
                    .set(Order::getUpdateTime,new Date())
                    .eq(Order::getId,order.getId())
                    .update();
        }




//        list.forEach(order -> {
//
//            // 删除订单详情
//            orderDetailMapper.deleteById(order.getId());
//            // 删除物流信息
//            orderLogisticsMapper.deleteById(order.getId());
//            // 删除订单
//            this.removeById(order.getId());
//        });
    }
}
